package com.gxa.pingan.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.gxa.pingan.common.JsonResult;
import com.gxa.pingan.exception.BusinessException;
import com.gxa.pingan.pojo.City;
import com.gxa.pingan.pojo.OrderVo;
import com.gxa.pingan.pojo.Shop;
import com.gxa.pingan.service.ShopService;
import com.gxa.pingan.utils.CastListUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@ResponseBody
@Controller
@RequestMapping("/shop")
@Api(value = "商店控制器",tags = "店铺的接口")
public class ShopController {
  private   static final Integer  SIZE=10;

    @Autowired
    ShopService shopService;



    @PostMapping("/findByPage")
    @ApiOperation("分页查询的方法")
    @ApiImplicitParams(value = {@ApiImplicitParam(name = "page",value = "传递查询的页码"),
            @ApiImplicitParam(name="size",value = "传入每页的记录数"),@ApiImplicitParam(name = "storesType",value = "传入店铺的类型")})
    public Map findByPage(Integer page,Integer size,Integer storesType){
        List<Map> all = shopService.findAll(storesType);
        List<Map> list = shopService.selectFindByPage(page, size,storesType);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setData(list);
        jsonResult.put("count",all.size());
        return jsonResult.getDataMap();
    }

    @PostMapping("/delete")
    @ApiOperation("删除店铺方法")
    @ApiImplicitParams(value = {@ApiImplicitParam(name = "id",value = "删除时需要的id号",required = true)})
    public  Map delete(Long id){
           shopService.delete(id);
           JsonResult jsonResult=new JsonResult();
           jsonResult.setCode("1");
           jsonResult.setMsg("删除成功");
           return jsonResult.getDataMap();
    }

    @PostMapping("/add")
    @ApiOperation("添加店铺的方法")
    @ApiImplicitParams(value = {@ApiImplicitParam(value = "传入的shop类型的JSON字符串",name = "map",type = "JSON",required = true)})
    public Map add(@RequestBody Map map) throws Exception {
        shopService.add(map);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("添加成功");
        return jsonResult.getDataMap();
    }
    @PostMapping("/update")
    @ApiOperation("修改店铺的操作")
    @ApiImplicitParams(value = {@ApiImplicitParam(value = "传入shop类型的JSON字符串",name = "shop",type = "JSON",required = true,dataType = "body")})
    public Map update(@RequestBody Shop shop) throws BusinessException {
        System.out.println(shop);
        shopService.update(shop.getId(),shop);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("修改成功");
        return  jsonResult.getDataMap();
    }

    @PostMapping("/findLikeByNameAndPage")
    @ApiOperation("这是分页模糊查询店铺的操作")
    @ApiImplicitParams(value = {@ApiImplicitParam(name = "map",value = "参数列表")})
    public Map findLikeByNameAndPage(@RequestBody Map map){
        List<Map> likeByName = shopService.findLikeByName((String) map.get("name"), (Integer) map.get("type"));

        List<Map> likeByNameAndPage = shopService.findLikeByNameAndPage((String) map.get("name"), (Integer) map.get("type"), (Integer) map.get("page"),(Integer)map.get("size"));
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("1");
        jsonResult.put("count",likeByName.size());
        jsonResult.setData(likeByNameAndPage);
        return jsonResult.getDataMap();

    }
/*
    @GetMapping("/exportShopList")
    @ApiOperation(value = "导出商店数据的接口方法")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "商店类型", required = true, dataType = "int"),
            @ApiImplicitParam(name = "name", value = "查询姓名", required = false, dataType = "string"),

    })
    public ResponseEntity<byte[]> exportOrderList(Integer type,String name
                                                ) throws IOException {
        // 查询到需要导出的集合
        List<Shop> all = shopService.findLikeByNameAndPageOrFindAll(type,name);
        System.out.println(all);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 语雀的核心写操作
        EasyExcel.write(outputStream, Shop.class).sheet("商店信息表").doWrite(all);
        // 缓冲数组`
        byte[] bytes = outputStream.toByteArray();
        // 获取请求头信息
        HttpHeaders httpHeaders = new HttpHeaders();
        // 设置请求头,告诉浏览器，以附件方式打开，而不是在页面上浏览
        httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode("商店信息表.xlsx", "utf-8"));

        return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
    }

    */
        @PostMapping("/exportShopList")
        @ApiOperation(value = "导出商店数据的接口方法")
        public void exportOrderList(@RequestBody Map<String, Object> exportList, HttpServletResponse response) throws IOException, BusinessException {
            Object object = exportList.get("exportShop");
            List<Integer> idList = CastListUtil.castList(object, Integer.class);

            List<Shop> list=new ArrayList<>();
            for (int i=0;i<idList.size();i++){
                Shop byId = shopService.findById(Long.valueOf(idList.get(i)));
                list.add(byId);
            }
            System.out.println(list);

            // 声明输出流对象
            ServletOutputStream out = null;
            // 编辑生成表格文件的文件名
            String excelName = "选中订单导出-" + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())) + ".xlsx";
            // 设置请求头信息,告诉前端以附件形式下载
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName, "utf-8"));
            // 接收输出流对象
            out = response.getOutputStream();
            // 调用语雀的写表格方法
            EasyExcelFactory.write(out, Shop.class).
                    registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet("选中订单的导出表").doWrite(list);
            if (out != null) {
                out.close();
            }
        }

}
